package com.btl.service.ai.support.input.reply;

import cn.idev.excel.context.AnalysisContext;// 实现 ReadListener 接口，设置读取数据的操作
import cn.idev.excel.read.listener.ReadListener;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.btl.service.ai.biz.constants.SegmentStatusEnum;
import com.btl.service.ai.biz.entity.KwSegment;
import com.btl.service.ai.biz.entity.KwSegmentQuestion;
import com.btl.service.ai.biz.service.IKwSegmentQuestionService;
import com.btl.service.ai.biz.service.IKwSegmentService;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;


/**
 * Faq模板读取
 */
@Slf4j
@Getter
public class FaqExcelDataListener implements ReadListener<FaqData> {

    private static final int BATCH_SIZE = 100;

    private final IKwSegmentService iKwSegmentService;
    private final IKwSegmentQuestionService iKwSegmentQuestionService;
    private final Long documentId;
    private final Long childId;

    public FaqExcelDataListener(IKwSegmentService iKwSegmentService, IKwSegmentQuestionService iKwSegmentQuestionService, Long documentId, Long childId) {
        this.iKwSegmentService = iKwSegmentService;
        this.iKwSegmentQuestionService = iKwSegmentQuestionService;
        this.documentId = documentId;
        this.childId = childId;
    }

    private final List<KwSegment> kwSegments = new ArrayList<>();
    private final List<KwSegmentQuestion> kwSegmentQuestions = new ArrayList<>();
    private int seqId = 1;
    private int segmentCount;
    private int codePointCount;

    @Override
    public void invoke(FaqData data, AnalysisContext context) {
        Long id = IdWorker.getId();
        String title = data.getTitle();
        String content = data.getContent();
        String questions = data.getQuestions();
        int titleCodePointCount = title
                .codePointCount(0, title
                        .length());
        int contentCodePointCount = content
                .codePointCount(0, content
                        .length());
        int segmentCodePointCount = titleCodePointCount + contentCodePointCount;
        codePointCount += segmentCodePointCount;
        KwSegment kwSegment = KwSegment.builder()
                .childId(childId)
                .id(id)
                .codePointCount(titleCodePointCount + contentCodePointCount)
                .seqId(seqId++)
                .documentId(documentId)
                .status(SegmentStatusEnum.WAITING.name())
                .segment(content)
                .title(title)
                .createTime(LocalDateTime.now())
                .updateTime(LocalDateTime.now())
                .vectorId(UUID.randomUUID()
                        .toString())
                .build();
        segmentCount++;
        List<String> questionSplit = Arrays.stream(
                        questions != null ? questions.split("\\r?\\n") : new String[0]
                )
                .map(String::trim)           // 去掉前后空格
                .filter(s -> !s.isEmpty())   // 过滤空行
                .toList();
        questionSplit.forEach(question -> {
            KwSegmentQuestion kwSegmentQuestion = KwSegmentQuestion.builder()
                    .segmentId(kwSegment.getId())
                    .documentId(documentId)
                    .question(question)
                    .createTime(LocalDateTime.now())
                    .updateTime(LocalDateTime.now())
                    .build();
            kwSegmentQuestions.add(kwSegmentQuestion);
        });
        kwSegments.add(kwSegment);
        if (kwSegments.size() >= BATCH_SIZE) {
            iKwSegmentService.saveBatch(kwSegments);
            kwSegments.clear();
            if (!kwSegmentQuestions.isEmpty()) {
                iKwSegmentQuestionService.saveBatch(kwSegmentQuestions);
                kwSegmentQuestions.clear();
            }
        }

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        if (!kwSegments.isEmpty()) {
            iKwSegmentService.saveBatch(kwSegments);
        }
        if (!kwSegmentQuestions.isEmpty()) {
            iKwSegmentQuestionService.saveBatch(kwSegmentQuestions);
        }
        log.info("reply文档数据-解析完成！");
    }
}
